package top.italks.safemodule;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import static top.italks.safemodule.AndroidSafe.TAG;

import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.util.Locale;
/*签名保护
* 1、校验签名是否和真实签名一致；
* 2、
*
*
* */
//https://dun.163.com/news/p/c280a974f0e04c179010de31568276b9

public class SignUtils {
    private static Context mContext;
    public SignUtils(Context context) {
        mContext=context;
    }
    //输入真实的签名
    public boolean getSingInfo(String keySHA256) throws PackageManager.NameNotFoundException, CertificateException {

        try {
            PackageInfo info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName()
                    , PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA256");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            Log.d(TAG,"应用当前签名="+result);
            if (result.equals(keySHA256)){
                return true;
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public String getSignSHA256(){
        try {
            PackageInfo info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName()
                    , PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA256");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            return  hexString.toString();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
